package com.service.single.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 通过切面实现注解
 */
@Aspect
@Component
public class LogRecordAspect {

    /**
     * 声明一个切面
     *
     * @Pointcut("execution(public * com.service.single.controller.*.*(..)) && @annotation(LogRecord)")
     */
    @Pointcut("execution(public * com.service.single.controller.*.*(..))")
    public void webLog() {
    }

    /**
     * 前置通知
     */
    @Before("webLog()")
    public void before(JoinPoint joinPoint) {
        MethodSignature sign = (MethodSignature) joinPoint.getSignature();
        Method method = sign.getMethod();
        //获取方法上的注解
        LogRecord annotation = method.getAnnotation(LogRecord.class);
        if (annotation != null) {
            // 获取注解上的参数
            String value = annotation.value();
            System.out.println(value);
        }
    }

    private static final String[] HEADERS_TO_TRY = {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP",
            "HTTP_X_FORWARDED_FOR", "HTTP_X_FORWARDED", "HTTP_X_CLUSTER_CLIENT_IP", "HTTP_CLIENT_IP",
            "HTTP_FORWARDED_FOR", "HTTP_FORWARDED", "HTTP_VIA", "REMOTE_ADDR"};

    /**
     * 获取ip地址
     */
    private String getClientIpAddress(HttpServletRequest request) {
        for (String header : HEADERS_TO_TRY) {
            String ip = request.getHeader(header);
            if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
                return ip;
            }
        }
        return request.getRemoteAddr();
    }
}
